
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：返佣记录                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-01-30 13:56:19                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： RebateRecordService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.NPOI;
using BestTrader.Cms.NPOI.Extensions;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.ViewModels.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BestTrader.Cms.Services
{
    public class RebateRecordService : IRebateRecordService
    {
        private readonly IRebateRecordRepository _repository;
        private readonly IManagerService _managerService;
        private readonly IRebateExtractService _rebateExtractService;
        private readonly IMapper _mapper;

        public RebateRecordService(IRebateRecordRepository repository, IManagerService managerService, IRebateExtractService rebateExtractService, IMapper mapper)
        {
            _repository = repository;
            _managerService = managerService;
            _mapper = mapper;
            _rebateExtractService = rebateExtractService;
        }

        public RebateStatisticsModel GetRebateRecordByAgentId(int managerId, DateTime start, DateTime end, string UserId, string RoleId)
        {
            var _managers = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(managerId.ToString());

            var conditions = $"where TransactionTime >= '{start}' and TransactionTime<= '{end}' ";
            if (_managers.Any()) conditions += $"and ManagerId in({ String.Join(',', _managers.Select(p => p.ItemCode)) })";

            var list = _repository.GetList(conditions);

            var total = list.Sum(p => p.RebateRMBMoney);
            var titles = from order in list
                         group order by new { order.ManagerName, order.ManagerRealName, order.PManagerRealName } into g
                         select $"{ g.Key.PManagerRealName }>>>{g.Key.ManagerName}>>>{g.Key.ManagerRealName}";

            var data = from order in list
                       select new RebateDataModel
                       {
                           Title = $"{order.PManagerRealName}的直客{order.ManagerName}交易了{order.Quantity}手{order.ProjectCode}",
                           Date = order.TransactionTime?.ToString("MM-dd")
                       };

            var result = new RebateStatisticsModel
            {
                SelfTotal = total,
                Total = total,
                AgentTotal = 0,
                TerminalNum = titles.Count(),
                TerminalInfo = titles,
                RebateData = data,
                CostCoin = 0
            };
            //角色为3的用户显示代理返佣 ，自己返佣设置0  by  2019/02/28
            if (RoleId == "3")
            {
               // GetTotalByRecordConditions();
                result.AgentTotal = result.SelfTotal;
                result.SelfTotal = 0;
                //result.CostCoin = _rebateExtractService.GetTotalMoneyByManagerId(UserId.ToString());
                result.CostCoin = _rebateExtractService.GetTotalCostByManagerId(managerId.ToString(), start, end, UserId == managerId.ToString());

            }

            return result;
        }
        /// <summary>
        /// APP端首页统计接口
        /// </summary>
        /// <param name="managerId"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public HomeRebateRecordModel GetAppRebateRecordByAgentId(int managerId, DateTime start, DateTime end, string UserId, string RoleId)
        {
            var _managers = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(managerId.ToString());

            var conditions = $"where TransactionTime >= '{start}' and TransactionTime<= '{end}' ";
            if (_managers.Any()) conditions += $"and ManagerId in({ String.Join(',', _managers.Select(p => p.ItemCode)) })";

            var list = _repository.GetList(conditions);

            var total = list.Sum(p => p.RebateRMBMoney);
            var titles = from order in list
                         group order by new { order.ManagerName, order.ManagerRealName, order.PManagerRealName } into g
                         select $"{ g.Key.PManagerRealName }>>>{g.Key.ManagerName}>>>{g.Key.ManagerRealName}";


            //var data = from order in list
            //           select new RebateDataModel
            //           {
            //               Title = $"{order.PManagerRealName}的直客{order.ManagerName}交易了{order.Quantity}手{order.ProjectCode}",
            //               Date = order.TransactionTime?.ToString("MM-dd")
            //           };

            //总交易额: totalTrade 总返佣额: totalRebate 自己返佣：selfRebate 
            //代理返佣：agentRebate 活跃直客：activityCustomNum 产品类型数组：productTypes 产品各类型交易数的数组：productTrades

            var result = new HomeRebateRecordModel
            {
                SelfRebate = total,
                TotalRebate = total,
                AgentRebate = 0,
                ActivityCustomNum = titles.Count(),
                CostCoin = 0
            };
            //角色为3的用户显示代理返佣 ，自己返佣设置0  by  2019/02/28
            if (RoleId == "3")
            {
                result.AgentRebate = result.SelfRebate;
                result.SelfRebate = 0;
                result.CostCoin = _rebateExtractService.GetTotalCostByManagerId(managerId.ToString(), start, end, UserId == managerId.ToString());

            }

            return result;
        }
        /// <summary>
        /// 返佣记录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>

        public TableDataModel LoadData(RebateRecordRequestModel model, String userId, String roleId)
        {
            var _managers = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(userId, roleId);

            string conditions = "where IsDelete=0 ";//未删除的
            string Key = "";

            if (_managers.Any()) conditions += $"and ManagerId in({ String.Join(',', _managers.Select(p => p.ItemCode)) }) ";
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and ( ParentManagerName like @Key or PManagerRealName like @Key or  ManagerRealName like @Key or ManagerName like @Key )";
                Key = model.Key.ToSqlLikeParam();
            }
            if (!model.State.IsNullOrWhiteSpace())
            {
                conditions += $"and (ManagerId = {model.State} or ParentManagerId = {model.State})";
            }
            //比如说3月9日早六点开始到3月10日凌晨5点这段时间里做的交易都算3月9日这个交易日的对吧  +1 或者 =1  结算规则
            if (model.Start.HasValue)
            {
                // 0 按交易日  1 按结算日
                if (!model.SearchDateType.IsNullOrWhiteSpace() && model.SearchDateType == "1")
                {
                    conditions += $"and TransactionTime >='{  model.Start.Value.AddHours(6) }'";
                }
                else
                {
                    conditions += $"and TransactionTime >='{  model.Start.Value }'";
                }
            }
            if (model.End.HasValue)
            {
                //conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }'";
                if (!model.SearchDateType.IsNullOrWhiteSpace() && model.SearchDateType == "1")
                {
                    conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddHours(6).AddSeconds(-1) }'";
                }
                else
                {
                    conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }'";

                }
            }
            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc", new
            {
                Key = Key
            }).ToList();

            //核算总结果
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions, new { Key = Key }),
                data = list
            };
        }

        public string ExportExcel(RebateRecordRequestModel model, String userId, String roleId)
        {
            var excel = new ExcelFile<RebateRecordExcelModel>
            {
                FileDownloadName = $"返佣记录{DateTime.Now.ToString("_yyyy_MM_dd")}.xlsx",
                IsSeq = true,
                Title = "",
                Names = new List<string>() { "直客帐号", "直客姓名", "上级帐号", "上级姓名", "手续费(单边)", "成交时间", "开平数量", "货币类型", "产品类型", "产品名称", "备注", "返佣金额", "人民币金额" },
                Data = LoadExportData(model, userId, roleId)
            };

            var serverFilePath = excel.ToExcel();
            return serverFilePath;
        }

        public IEnumerable<RebateRecordExcelModel> LoadExportData(RebateRecordRequestModel model, String userId, String roleId)
        {
            var _managers = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(userId, roleId);

            string conditions = "where IsDelete=0 ";//未删除的
            string Key = "";

            if (_managers.Any()) conditions += $"and ManagerId in({ String.Join(',', _managers.Select(p => p.ItemCode)) }) ";
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and (ParentManagerName like @Key or PManagerRealName like @Key or  ManagerRealName like @Key or ManagerName like @Key )";
                Key = model.Key.ToSqlLikeParam();
            }
            if (!model.State.IsNullOrWhiteSpace())
            {
                conditions += $"and (ManagerId = {model.State} or ParentManagerId = {model.State})";
            }
            //比如说3月9日早六点开始到3月10日凌晨5点这段时间里做的交易都算3月9日这个交易日的对吧  +1 或者 =1  结算规则
            if (model.Start.HasValue)
            {
                // 0 按交易日  1 按结算日
                if (!model.SearchDateType.IsNullOrWhiteSpace() && model.SearchDateType == "1")
                {
                    conditions += $"and TransactionTime >='{  model.Start.Value.AddHours(6) }'";
                }
                else
                {
                    conditions += $"and TransactionTime >='{  model.Start.Value }'";
                }
            }
            if (model.End.HasValue)
            {
                //conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }'";
                if (!model.SearchDateType.IsNullOrWhiteSpace() && model.SearchDateType == "1")
                {
                    conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddHours(6).AddSeconds(-1) }'";
                }
                else
                {
                    conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }'";

                }
            }

            var result = new List<RebateRecordExcelModel>();
            //var UnitNames = new Dictionary<string, string>() { { "HKD", "HK" }, { "USD", "$" }, { "EUR", "€" }, { "JPY", "￥" }, { "CNY", "￥" } };

            var list = _repository.GetList(conditions, new
            {
                Key = Key
            }).OrderBy(p => p.AddTime).OrderBy(p => p.ParentManagerId);

            var pGroup = list.GroupBy(p => p.ParentManagerId).Select(p => p.Key ?? 0).ToList();
            var aGroup = list.GroupBy(p => p.ManagerId).Select(p => p.Key).ToList();
            // 所有 代理
            var parentIds = aGroup.Intersect(pGroup);
            var parentManagerIds = list.Where(p=> parentIds.Contains(p.ParentManagerId??0)).GroupBy(p => p.ManagerId).Select(p => p.Key).ToList();
            // 除代理外的其他用户
            var oGroup = aGroup.Intersect(parentIds);
            var otherIds = aGroup.Except(parentManagerIds);

            foreach (var parentId in parentIds)
            {
                var parents = list.Where(p => p.ManagerId == parentId).ToList();
                var items = _mapper.Map<List<RebateRecordExcelModel>>(parents);
                result.AddRange(items);
                var childs = list.Where(p => p.ParentManagerId == parentId).OrderBy(p => p.ManagerId).ToList();
                var itemChilds = _mapper.Map<List<RebateRecordExcelModel>>(childs);
                result.AddRange(itemChilds);
            }

            var others = list.Where(p => otherIds.Contains(p.ManagerId)).OrderBy(p => p.ManagerId).ToList();
            var itemOthers = _mapper.Map<List<RebateRecordExcelModel>>(others);
            result.AddRange(itemOthers);

            return result;
        }


        /// <summary>
        /// 获取核算总计根据筛选条件
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public TableDataModel GetTotalByRecordConditions(RebateRecordRequestModel model, String userId, String roleId)
        {

            var _managers = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(userId, roleId);

            string conditions = "where IsDelete=0 ";//未删除的
            string Key = "";

            if (_managers.Any()) conditions += $"and ManagerId in({ String.Join(',', _managers.Select(p => p.ItemCode)) }) ";
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and ( ParentManagerName like @Key or PManagerRealName like @Key or  ManagerRealName like @Key or ManagerName like @Key )";
                Key = model.Key.ToSqlLikeParam();
            }
            if (!model.State.IsNullOrWhiteSpace())
            {
                conditions += $"and (ManagerId = {model.State} or ParentManagerId = {model.State})";
            }
            if (model.Start.HasValue)
            {
                // 0 按交易日  1 按结算日
                if (!model.SearchDateType.IsNullOrWhiteSpace() && model.SearchDateType == "1")
                {
                    conditions += $"and TransactionTime >='{  model.Start.Value.AddHours(6) }'";
                }
                else
                {
                    conditions += $"and TransactionTime >='{  model.Start.Value }'";
                }
            }
            if (model.End.HasValue)
            {
                if (!model.SearchDateType.IsNullOrWhiteSpace() && model.SearchDateType == "1")
                {
                    conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddHours(6).AddSeconds(-1) }'";
                }
                else
                {
                    conditions += $"and TransactionTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }'";
                }
            }

            var list = _repository.GetList(conditions,new
            {
                Key=Key
            }).OrderBy(item => item.Id).ToList();

            var total = new
            {
                TotalQuantity = list.Sum(p => p.Quantity),
                TotalRebateMoney = list.Sum(p => p.RebateMoney),
                TotalRebateRMBMoney = list.Sum(p => p.RebateRMBMoney)
            };

            var result = new TableDataModel()
            {
                count = list.Count(),
                data = total
            };
            return result;
        }
    }
}